import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Cookies from 'js-cookie'

// create an axios instance
const service = axios.create({
  baseURL: config.BASE_API, // api的base_url
  timeout: 500000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  const lang = Cookies.get('language') || 'en_US'
  if (lang) {
    config.headers['x-access-lang'] = lang
  }

  if (store.getters.token) {
    config.headers['x-access-token'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
  }
  if (config.params && config.params.responseType) {
    config.responseType = 'arraybuffer'
  }
  return config
}, error => {
  // Do something with request error
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    const code = res.result_code
    if (code && code !== '0' && code !== 'loginSuccess') {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })

      if (code === 'tokenInvalid' || code === 'tokenExpired' || code === 'ipDifferentTokenIp' || code === 'sessionTimeout') {
        store.dispatch('FedLogOut').then(() => {
          location.reload()// 为了重新实例化vue-router对象 避免bug
          this.$router.push({ path: '/login' })
        })
      }
      return Promise.reject('error')
    } else {
      return response
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export default service
